package com.chenfan.mcn.mq.producer;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chenfan.mcn.clients.privilege.PrivilegeClient;
import com.chenfan.mcn.clients.privilege.ScompanyRes;
import com.chenfan.mcn.constant.NumberCst;
import com.chenfan.mcn.dao.*;
import com.chenfan.mcn.enums.AccountTypeEnum;
import com.chenfan.mcn.enums.FinanceArapTypeEnum;
import com.chenfan.mcn.enums.FinanceChargeTypeEnum;
import com.chenfan.mcn.enums.FinanceSettTemplateEnum;
import com.chenfan.mcn.exception.McnErrorCode;
import com.chenfan.mcn.model.*;
import com.chenfan.mcn.mq.AbstractMessageProducer;
import com.chenfan.mcn.mq.MessageProducer;
import com.chenfan.mcn.mq.message.ChargeAutoInvoiceMessage;
import com.chenfan.mcn.mq.message.CfChargeCommonMessage;
import com.chenfan.mcn.service.StarMonthlySettlementService;
import com.chenfan.mcn.utils.BusinessAssert;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 红人月度结算单MQ消息生产者
 *
 * @author wulg
 * @date 2022-01-15
 **/
@Slf4j
@Component
public class StarMonthlySettlementMessageProducer extends AbstractMessageProducer implements MessageProducer<Long> {

    @Autowired
    private StarMonthlySettlementMapper settlementMapper;

    @Autowired
    private StarMonthlySettlementSubMapper settlementSubMapper;

    @Autowired
    private PrivilegeClient privilegeClient;

    @Autowired
    private StarAccountInfoMapper starAccountInfoMapper;

    @Autowired
    private StarBasicDataMapper starBasicDataMapper;

    @Async
    @Override
    public void asyncSendRecordToMq(Long settlementId) {
        log.info("【红人月度结算单】开始生成费用MQ消息，settlementId={}",settlementId);
        StarMonthlySettlement starMonthlySettlement = settlementMapper.selectById(settlementId);
        BusinessAssert.notNull(starMonthlySettlement, McnErrorCode.DATA_NOT_FOUND, "查询不到结算单");
        //查询子结算单
        List<StarMonthlySettlementSub> subList = settlementSubMapper.selectList(Wrappers.lambdaQuery(StarMonthlySettlementSub.class)
                .eq(StarMonthlySettlementSub::getSettlementId, settlementId)
                .eq(StarMonthlySettlementSub::getIsDelete, NumberCst.ZERO));
        BusinessAssert.notEmpty(subList, McnErrorCode.DATA_NOT_FOUND, "查询不到子结算单");
        StarBasicData starBasicData = starBasicDataMapper.selectById(starMonthlySettlement.getStarId());
        BusinessAssert.notNull(starBasicData, McnErrorCode.DATA_NOT_FOUND, "查询不到该红人");
        StarAccountInfo starAccountInfo = starAccountInfoMapper.selectById(starMonthlySettlement.getStarAccountId());
        BusinessAssert.notNull(starAccountInfo, McnErrorCode.DATA_NOT_FOUND, "查询不到红人收款账户信息");
        List<ChargeAutoInvoiceMessage> invoiceMessageList = new ArrayList<>(subList.size());
        //开票信息
        List<ScompanyRes> companyResList = privilegeClient.getParList().getObj();
        Map<Long, String> companyMap = companyResList.stream().collect(Collectors.toMap(k -> k.getCompanyId(), v -> v.getParentCompanyName()));
        for(StarMonthlySettlementSub sub : subList) {
            CfChargeCommonMessage chargeMessage = this.buildChargeMessage(starMonthlySettlement, sub, starAccountInfo, companyMap, starBasicData);
            invoiceMessageList.add(this.buildAutoInvoiceMessage(starMonthlySettlement, chargeMessage));
        }
        if(CollectionUtils.isNotEmpty(invoiceMessageList)) {
            //发送费用+自动生成账单消息
            invoiceMessageList.forEach(invoiceMessage -> {
                this.doSendRecordToMq(starMonthlySettlement.getSettlementCode(), invoiceMessage, this.financeTopic);
            });
            //检查费用生成情况
            this.checkCharge(starMonthlySettlement.getSettlementCode());
        }
    }

    /**
     * 构建费用消息
     * @return
     */
    private  CfChargeCommonMessage buildChargeMessage(StarMonthlySettlement starMonthlySettlement, StarMonthlySettlementSub sub, StarAccountInfo starAccountInfo, Map<Long, String> companyMap, StarBasicData starBasicData) {
        CfChargeCommonMessage chargeMessage = new CfChargeCommonMessage();
        chargeMessage.setChargeType(FinanceChargeTypeEnum.STAR_MONTHLY_SETTLEMENT_CHARGE.getType());
        chargeMessage.setArapType(FinanceArapTypeEnum.PAY.getType());
        chargeMessage.setChargeSourceCode(starMonthlySettlement.getSettlementCode());
        chargeMessage.setChargeSourceDetail(sub.getSubSettlementCode());
        chargeMessage.setAmountPp(sub.getFinancePaidAmount());
        chargeMessage.setPricePp(chargeMessage.getAmountPp());
        //红人收款账户的【户名】
        chargeMessage.setBalance(starBasicData.getStarNickname());
        //子结算单 ：我司签约主体
        chargeMessage.setFinanceEntity(companyMap.get(sub.getContractingId()));
        chargeMessage.setCreateBy(starMonthlySettlement.getCreateBy());
        chargeMessage.setCreateName(starMonthlySettlement.getCreateName());
        chargeMessage.setCreateDate(new Date());
        chargeMessage.setUpdateBy(chargeMessage.getCreateBy());
        chargeMessage.setUpdateDate(chargeMessage.getCreateDate());
        chargeMessage.setUpdateName(chargeMessage.getCreateName());
        chargeMessage.setTenantId(starMonthlySettlement.getTenantId());
        chargeMessage.setCompanyId(starMonthlySettlement.getCompanyId());
        chargeMessage.setDepartmentId(starMonthlySettlement.getDepartmentId());
        chargeMessage.setSettTemplate(FinanceSettTemplateEnum.STAR_MONTHLY_SETTLEMENT.getType());
        chargeMessage.setTaxRate(BigDecimal.ZERO);

        chargeMessage.setAccountId(starMonthlySettlement.getStarAccountId());
        chargeMessage.setBalanceType(NumberCst.ONE);
        return chargeMessage;
    }

    /**
     * 构建自动生成账单报文
     * @param charge
     * @return
     */
    private ChargeAutoInvoiceMessage buildAutoInvoiceMessage(StarMonthlySettlement starMonthlySettlement, CfChargeCommonMessage charge) {
        ChargeAutoInvoiceMessage message = new ChargeAutoInvoiceMessage();
        //业务类型：1-货品采购; 2-销售订单; 3-MCN; 4-WMS
        message.setChargeSourceType(3);
        message.setChargeInfos(Lists.newArrayList(charge));
        //打款账户id 即我司合同签约主体id
//        message.setAccountId(sub.getContractingId());
//        message.setAccountType(AccountTypeEnum.COMPAY_ACCOUNT.getType());
//        message.setAccountName(AccountTypeEnum.COMPAY_ACCOUNT.getDesc());
//        message.setCustomerInvoiceWay(NumberCst.ONE);
        message.setCreateBy(starMonthlySettlement.getCreateBy());
        message.setCreateName(starMonthlySettlement.getCreateName());
        message.setCreateDate(new Date());
        message.setUpdateBy(starMonthlySettlement.getCreateBy());
        message.setUpdateName(starMonthlySettlement.getCreateName());
        message.setUpdateDate(starMonthlySettlement.getCreateDate());
        message.setTenantId(starMonthlySettlement.getTenantId());
        message.setCompanyId(starMonthlySettlement.getCompanyId());
        message.setDepartmentId(starMonthlySettlement.getDepartmentId());
         return message;
    }
}
